<template>
  <el-drawer title="数据源配置" size="1200" v-model="visible" destroy-on-close @closed="$emit('closed')">
    <el-container style="border-top: solid 1px #e4e7ed;border-bottom: solid 1px #e4e7ed;margin: 0px 15px;">
      <el-aside width="220px">
        <el-container>
          <el-header>
            <el-input placeholder="输入关键字进行过滤" v-model="modelFilterText" clearable></el-input>
          </el-header>
          <el-main class="nopadding" style="background: #fff;padding-top: 10px;">
            <template v-if="modelList.length>0">
              <el-tree ref="models" class="menu" node-key="id" default-expand-all :data="modelList" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="modelFilterNode" :current-node-key="modelId" @node-click="modelClick" v-loading="loading.model">
                <template #default="{node, data}">
                  <span class="custom-tree-node" :class="data.status=='1'?'disabled':''">
                    <span class="label">{{ data.tableComment }}</span>
                    <span class="code">{{ data.tableName }}</span>
                    <span class="do" v-if="data.id != ''">
                      <el-button-group>
                        <el-popconfirm title="确定要重置吗？" >
                          <template #reference>
                            <el-button icon="el-icon-refresh" size="small" @click.stop="refreshFields(node, data)"></el-button>
                          </template>
                        </el-popconfirm>
                      </el-button-group>
                    </span>
                  </span>
                </template>
              </el-tree>
            </template>
            <template v-else>
              <el-empty description="暂无数据模型" :image-size="100" style="margin-top: 100px"></el-empty>
            </template>
          </el-main>
          <el-footer style="height:51px;text-align: center;">
            <el-button-group style="width: 100%">
              <el-button type="primary" size="small" icon="el-icon-office-building" @click="modelManager" style="width: 100%">管理数据模型</el-button>
            </el-button-group>
          </el-footer>
        </el-container>
      </el-aside>
      <el-container v-if="modelId==null">
        <el-main class="nopadding">
          <el-empty description="请先选择左侧模型后再操作" :image-size="100" style="margin-top: 200px"></el-empty>
        </el-main>
      </el-container>
      <el-container v-else>
        <el-header>
          <div class="left-panel">
            <el-alert :title="title" type="success" :closable="false"></el-alert>
          </div>
          <div class="right-panel">
            <div class="right-panel-search">
              <el-button type="primary" icon="el-icon-edit" @click="save">保 存</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <el-tabs v-model="activeName" type="card" class="tabs-header">
            <el-tab-pane name="dataTable" label="数据表">
              <jd-table ref="table" :data="fieldList" row-key="id" stripe hidePagination hideDo>
                <el-table-column prop="id" label="序号" width="80"></el-table-column>
                <el-table-column prop="comment" label="名称"></el-table-column>
                <el-table-column prop="field" label="字段"></el-table-column>
                <el-table-column prop="type" label="类型" align="center"></el-table-column>
                <el-table-column prop="length" label="长度" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="100">
                  <template #default="scope">
                    <el-button-group>
                      <el-button text type="primary" class="button" @click="addColumn(scope.row)">加入</el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </jd-table>
            </el-tab-pane>
            <el-tab-pane name="dataFields" label="显示列">
              <jd-form-table v-model="columns" :addTemplate="addTemplate" :maxHeight="700" drag-sort placeholder="暂无数据">
                <el-table-column prop="label" label="显示名称" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.label" placeholder=""></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="prop" label="字段属性" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.prop" disabled></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="width" label="显示宽度" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.width" placeholder=""></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="hide" label="是否隐藏" align="center">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.hide"></el-checkbox>
                  </template>
                </el-table-column>
				<el-table-column prop="mate" label="查询配置" width="110">
					<template #default="scope">
						  <el-select v-model="scope.row.mate" placeholder="=" style="width:80px">
								  <el-option label="="  value="="></el-option>
								  <el-option label="!=" value="!="></el-option>
								  <el-option label=">" value=">"></el-option>
								  <el-option label=">=" value=">="></el-option>
								  <el-option label="<" value="<"></el-option>
								  <el-option label="<=" value="<="></el-option>
						  </el-select>
					</template>
				</el-table-column>
				  <el-table-column prop="control" label="控件配置" width="110">
					  <template #default="scope">
						  <el-select v-model="scope.row.control" placeholder="控件" style="width:80px">
							  <el-option v-for="item in controlList" :label="item.label" :value="item.value"></el-option>
						  </el-select>
					  </template>
				  </el-table-column>
                <el-table-column prop="sortable" label="字段排序" align="center">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.sortable"></el-checkbox>
                  </template>
                </el-table-column>
              </jd-form-table>
            </el-tab-pane>
			<el-tab-pane name="buttonConfig" label="按钮配置" v-if="appClassify == 0">
				<div class="button-call">
					<el-checkbox v-model="buttonConfig.submitBtn"  label="提交"></el-checkbox>
					<el-input v-model="buttonConfig.submitBtnText"/>
				</div>
				<div class="button-call">
					<el-checkbox v-model="buttonConfig.queryBtn"  label="查询"></el-checkbox>
					<el-input v-model="buttonConfig.queryBtnText"/>
				</div>
				<div class="button-call">
					<el-checkbox v-model="buttonConfig.resetBtn" label="重置"></el-checkbox>
					<el-input v-model="buttonConfig.resetBtnText"/>
				</div>
				<div class="button-call">
					<el-checkbox v-model="buttonConfig.printBtn" label="打印"></el-checkbox>
					<el-input v-model="buttonConfig.printBtnText"/>
				</div>
			</el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-container>
  </el-drawer>
</template>

<script>
export default {
  name: "dataSource",
  components: {

  },
  data() {
    return {
      visible: false,
      selection: [],
      loading: {
        model: false,
        field: true,
      },
      activeName: 'dataFields',
      formData:{

      },
      title:"",
      modelId: null,
      modelList: [],
      modelFilterText: '',
      fieldList: [],
      appId:null,
      addTemplate: {
        label: '',
        prop: '',
		    type:'',
        width: '100',
        hide: false,
        query: false,
        sortable: false,
        fixed: false,
        filters: [],
		mate:'='
      },
      buttonConfig:{
		  submitBtn:false,
		  submitBtnText:"提交表单",
		  queryBtn:true,
		  queryBtnText:"查询",
		  resetBtn:true,
		  resetBtnText:"重置",
		  printBtn:true,
		  printBtnText:"打印"
	  },
	  controlList:[
		  {label:"文本框",value:"1"},
		  {label:"下拉框",value:"2"},
		  {label:"单选框",value:"3"},
		  {label:"富文本",value:"4"},
		  {label:"表格表单",value:"5"},
		  {label:"上传组件",value:"6"},
		  {label:"部门组件",value:"7"},
		  {label:"地址组件",value:"8"},
		  {label:"图片组件",value:"9"},
	  ],
	  // 基本字段
	  baseFields:[
		  {
			  label: "创建者",
			  prop: "create_by",
			  type: "varchar",
			  width: 182,
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: true,
			  filters: [],
			  control:'1',
			  mate:'='
		  },
		  {
			  label: '创建时间',
			  prop: 'create_time',
			  type:'datetime',
			  width: '100',
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: false,
			  filters: [],
			  control:'1',
			  mate:'='
		  },
		  {
			  label: '更新者',
			  prop: 'update_by',
			  type:'varchar',
			  width: '100',
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: false,
			  filters: [],
			  control:'1',
			  mate:'='
		  },
		  {
			  label: '更新时间',
			  prop: 'update_time',
			  type:'datetime',
			  width: '100',
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: false,
			  filters: [],
			  control:'1',
			  mate:'='
		  },
		  {
			  label: '逻辑删除',
			  prop: 'del_flag',
			  type:'char',
			  width: '100',
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: false,
			  filters: [],
			  control:'1',
			  mate:'='
		  },
		  {
			  label: '备注',
			  prop: 'remark',
			  type:'varchar',
			  width: '100',
			  hide: false,
			  query: false,
			  sortable: false,
			  fixed: false,
			  filters: [],
			  control:'1',
			  mate:'='
		  },

	  ],
      active: 0,
      columns: [],
      columnList:[],
	  appClassify:1,
      assignColumns: true
    }
  },
  watch: {
    modelFilterText(val) {
      this.$refs.models.filter(val);
    },
    columns:{
      handler(){
        this.getTitle();
        this.getAddFields();
      },
      deep:true
    }
  },
  methods: {
    // 显示
    open(appId, modelId, columns,buttonConfig) {
	  if (buttonConfig != null && 'null' != buttonConfig && typeof(buttonConfig) != 'undefined'){
		  this.buttonConfig =JSON.parse(buttonConfig);
	  }
      this.visible = true;
      this.appId = appId;
      this.modelId = modelId;
      this.getAppInfo();
      // 加载模型列表
      this.getModles();
      // 加载模型字段
      if (this.modelId!=null){
        this.assignColumns = false;
        // 设置选中模型
        this.getFields(this.modelId);

        // 加入配置字段
        columns.forEach(item =>{
          var fieldItem = {
            label: item.comment,
            prop: item.field,
			      type: item.type,
            width: item.length,
            hide: item.hide,
            query: item.query,
            sortable: item.sortable,
            fixed: item.fixed,
            filters: []
          };
          this.columns.push(fieldItem);
        });
		this.baseFields.forEach((item)=>{
			if (!this.isHasObj(this.columns,item)){
				 this.columns.push(item)
			}
		})
      }
    },
	 // 获取应用信息
	 async getAppInfo() {
		 var res = await this.$API.app.appStore.getInfo.get(this.appId);
		 if (res.code == 200){
			 this.appClassify = res.data.appClassify;
		 }
	 },
	  isHasObj(arr, val){
			var flag = false; // true为有 false为没有
			for(var i=0; i<arr.length; i++) {
				if(arr[i].prop == val.prop) {
					flag = true;
					break;
				}
			}
			return flag ;
	},
	// 校验是否在显示列中
    isShow(field){
      for (let i = 0; i < this.columns.length; i++) {
        if (field == this.columns[i].prop){
          return false;
        }
      }
      return true;
    },
    // 获取可添加的字段
    getAddFields(){
      this.fieldList.map((item) =>{
        if (this.isShow(item.field)){
          this.columnList.push(item);
        }
      })
    },
	  // 允许查询
	 changeQuery(scope){
		 if (scope.row.query){
			 scope.row.mate ="="
		 }else {
			 scope.row.mate =""
		 }

	 },
    // 添加列
    addColumn(row){
      if (!this.isShow(row.field)){
        this.$message.error("该字段已加入显示列");
        return;
      }
      for (let i = 0; i < this.columnList.length; i++) {
        if (row.field == this.columnList[i].field){
          this.columnList.splice(i)
        }
      }
      var fieldItem = {
        label: row.comment,
        prop: row.field,
        type:row.type,
        width: '100',
        hide: false,
        query: false,
        sortable: false,
        fixed: false,
        filters: []
      };
      this.columns.push(fieldItem);

      this.$message.success("加入成功");
    },
    // 获取提示文字
    getTitle(){
      let message ="模型共"+ this.fieldList.length +"个字段，数据列表已设置了"+ this.columns.length +"项显示";
      this.title = message;
    },
    // 加载模型列表
    async getModles() {
      this.loading.model = true;
      var res = await this.$API.app.model.listModelByAppId.get({pageSize: 100, "appId": this.appId});
      if (res.code == 200) {
        this.modelList = res.data;
        this.loading.model = false;
      }
    },
    // 加载字段列表
    async getFields(modelId){
      this.loading.field = true;
      var res = await this.$API.app.model.getModelColumnList.get(modelId);
      if (res.code == 200){
        this.fieldList = res.data;
        this.loading.field = false;

        if (this.assignColumns){
			var result = await this.$API.app.model.getModelConfigById.get(modelId);
			if (result.code == 200){
				 this.columns = JSON.parse(result.data.fieldConfig)
			}
        }

		    this.getTitle();
      }
    },
    // 树过滤
    modelFilterNode(value, data){
      if (!value) return true;
      var targetText = data.tableName;
      return targetText.indexOf(value) !== -1;
    },
    // 模型树点击事件
    modelClick(data) {
		  this.columns = []
      if (this.modelId!=null){
        this.activeName = "dataTable";
      }
      this.modelId = data.id;
      this.assignColumns = true;
      // 加载字段列表
      this.getFields(data.id);
    },
    // 重置模型字段
    refreshFields(node, data){
      this.modelId = data.id;
      //this.getFields(data.id);
      this.$refs.models.setCurrentKey(this.modelId);
    },
    // 管理数据模型
    modelManager(){
      this.$router.push({
        path: '/app/model',
        query: {
          appId: this.appId
        }
      });
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection
    },
    // 保存
    async save() {
      for (let i = 0; i < this.columns.length; i++) {
        if (this.columns[i].prop == ''){
          this.columns.splice(i)
        }
		if (typeof(this.columns[i].mate)=='undefined'){
			this.columns[i].mate ='='
		}
		  if (typeof(this.columns[i].control)=='undefined'){
			  this.columns[i].control ='1'
		  }
      }
      this.formData.modelId = this.modelId;
      this.formData.fieldConfig = JSON.stringify(this.columns);
      this.formData.appId = this.appId;
	  this.formData.buttonConfig = JSON.stringify(this.buttonConfig)
      const res = await this.$API.system.dataList.addConfig.post(this.formData)
      if (res.code == 200){
        this.$emit('success', this.modelId, this.columns);
        this.$message.success("保存成功");
        this.visible = false;
      }else {
		  this.$message.error("保存失败");
		  this.visible = false;
	  }
    }
  },
}
</script>

<style lang="scss" scoped>
.menu:deep(.el-tree-node__label) {display: flex;flex: 1;height:100%;}
.custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 24px;height:100%;}
.custom-tree-node .code {font-size: 12px;color: #999;}
.custom-tree-node .do {display: none;}
.custom-tree-node:hover {color: #409eff;}
.custom-tree-node:hover .code {display: none;}
.custom-tree-node:hover .do {display: inline-block;animation: fadeIn;animation-duration: 1s;}
.custom-tree-node.disabled{text-decoration:line-through; color: #aaa;}
.custom-tree-node.disabled .code {font-size: 12px;color: #aaa;}

.tabs-header {
  :deep(.el-tabs__item):hover{
    span{
      color: #409eff;
    }
  }
  :deep(.el-tabs__item).is-active {
    background: #409eff;
    color: #FFFFFF;
    position: relative;
    span{
      color: #FFFFFF;
    }
  }
}
.button-call .el-checkbox{
	margin-right: 40px;
}
.button-call .el-input{
	width: 343px;
}
</style>
